package com.example.springboot1.Service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.example.springboot1.utils.ConstantPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;


@Service
public class OssService {
    public  boolean  delete(String objectName) {
        // 创建OSSClient实例。
        String endpoint="https://oss-cn-hangzhou.aliyuncs.com";
//        boolean flag = false;
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(ConstantPropertiesUtils.END_POINT, ConstantPropertiesUtils.ACCESS_KEY_ID, ConstantPropertiesUtils.ACCESS_KEY_SECRET);
            // 删除文件。
            ossClient.deleteObject(ConstantPropertiesUtils.BUCKET_NAME, objectName);
//            flag=true;
            // 关闭OSSClient。
            ossClient.shutdown();

        } catch (OSSException e){
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 上传返回路径
     */
    public String getFileUrl(MultipartFile file){
        //获取上传文件输入流
        try {
            InputStream inputStream = file.getInputStream();
            //以下思路是创建一个输出流来缓存
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) > -1) {
                baos.write(buffer, 0, len);
            }
            baos.flush();
            String md5 = DigestUtils.md5DigestAsHex(baos.toByteArray());
            InputStream inputStreamForMD5 = new ByteArrayInputStream(baos.toByteArray());
            InputStream inputStreamForOss = new ByteArrayInputStream(baos.toByteArray());
            //获取一个md加密
            String md5OfFileName = DigestUtils.md5DigestAsHex(inputStreamForMD5);
            //获取文件名称
            String fileName = file.getOriginalFilename();
//            取后缀
            String fileSuffix = fileName.substring(file.getOriginalFilename().lastIndexOf("."));
            //1 在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            // yuy76t5rew01.jpg
            fileName = uuid+md5OfFileName+fileSuffix;
            //2 把文件按照日期进行分类
            //获取当前日期
            //   2019/11/12
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //拼接
            //  2019/11/12/ewtqr313401.jpg
            fileName = datePath+"/"+fileName;
//            System.out.println("fileName"+fileName);
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(ConstantPropertiesUtils.END_POINT, ConstantPropertiesUtils.ACCESS_KEY_ID, ConstantPropertiesUtils.ACCESS_KEY_SECRET);
        /*
            创建PutObjectRequest对象。
            <yourObjectName>上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
            filePath:生成路径
        */
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(file.getSize());
//            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setContentEncoding("utf-8");
            objectMetadata.setContentType(ConstantPropertiesUtils.getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            // 上传文件。
//            ossClient.putObject(BUCKET_NAME, fileName, inputStream);
            PutObjectResult putResult = ossClient.putObject(ConstantPropertiesUtils.BUCKET_NAME, fileName, inputStreamForOss, objectMetadata);
//            PutObjectRequest putObjectRequest =ossClient.putObject(BUCKET_NAME,)
            // 关闭OSSClient。
            ossClient.shutdown();

            //返回地址
            String url = "https://"+ConstantPropertiesUtils.BUCKET_NAME+"."+ConstantPropertiesUtils.END_POINT+"/"+fileName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return "失败";
        }

    }
}
